<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Database transactions &mdash; Django 1.7.8.dev20150401230226 documentation</title>
    
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../../',
        VERSION:     '1.7.8.dev20150401230226',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <link rel="top" title="Django 1.7.8.dev20150401230226 documentation" href="../../index.html" />
    <link rel="up" title="Models and databases" href="index.html" />
    <link rel="next" title="Multiple databases" href="multi-db.html" />
    <link rel="prev" title="Performing raw SQL queries" href="sql.html" />



 
<script type="text/javascript" src="../../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head>
  <body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 1.7.8.dev20150401230226 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="sql.html" title="Performing raw SQL queries">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="multi-db.html" title="Multiple databases">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-db-transactions">
            
  <div class="section" id="s-module-django.db.transaction">
<span id="s-database-transactions"></span><span id="module-django.db.transaction"></span><span id="database-transactions"></span><h1>Database transactions<a class="headerlink" href="#module-django.db.transaction" title="Permalink to this headline">¶</a></h1>
<p>Django gives you a few ways to control how database transactions are managed.</p>
<div class="section" id="s-managing-database-transactions">
<span id="managing-database-transactions"></span><h2>Managing database transactions<a class="headerlink" href="#managing-database-transactions" title="Permalink to this headline">¶</a></h2>
<div class="section" id="s-django-s-default-transaction-behavior">
<span id="django-s-default-transaction-behavior"></span><h3>Django&#8217;s default transaction behavior<a class="headerlink" href="#django-s-default-transaction-behavior" title="Permalink to this headline">¶</a></h3>
<p>Django&#8217;s default behavior is to run in autocommit mode. Each query is
immediately committed to the database, unless a transaction is active.
<a class="reference internal" href="#autocommit-details"><em>See below for details</em></a>.</p>
<p>Django uses transactions or savepoints automatically to guarantee the
integrity of ORM operations that require multiple queries, especially
<a class="reference internal" href="queries.html#topics-db-queries-delete"><em>delete()</em></a> and <a class="reference internal" href="queries.html#topics-db-queries-update"><em>update()</em></a> queries.</p>
<p>Django&#8217;s <a class="reference internal" href="../testing/tools.html#django.test.TestCase" title="django.test.TestCase"><tt class="xref py py-class docutils literal"><span class="pre">TestCase</span></tt></a> class also wraps each test in a
transaction for performance reasons.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.6:</span> <p>Previous version of Django featured <a class="reference internal" href="#transactions-upgrading-from-1-5"><em>a more complicated default
behavior</em></a>.</p>
</div>
</div>
<div class="section" id="s-tying-transactions-to-http-requests">
<span id="s-id1"></span><span id="tying-transactions-to-http-requests"></span><span id="id1"></span><h3>Tying transactions to HTTP requests<a class="headerlink" href="#tying-transactions-to-http-requests" title="Permalink to this headline">¶</a></h3>
<p>A common way to handle transactions on the web is to wrap each request in a
transaction. Set <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASE-ATOMIC_REQUESTS"><tt class="xref std std-setting docutils literal"><span class="pre">ATOMIC_REQUESTS</span></tt></a> to
<tt class="docutils literal"><span class="pre">True</span></tt> in the configuration of each database for which you want to enable
this behavior.</p>
<p>It works like this. Before calling a view function, Django starts a
transaction. If the response is produced without problems, Django commits the
transaction. If the view produces an exception, Django rolls back the
transaction.</p>
<p>You may perform partial commits and rollbacks in your view code, typically with
the <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a> context manager. However, at the end of the view, either
all the changes will be committed, or none of them.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">While the simplicity of this transaction model is appealing, it also makes it
inefficient when traffic increases. Opening a transaction for every view has
some overhead. The impact on performance depends on the query patterns of your
application and on how well your database handles locking.</p>
</div>
<div class="admonition-per-request-transactions-and-streaming-responses admonition">
<p class="first admonition-title">Per-request transactions and streaming responses</p>
<p>When a view returns a <a class="reference internal" href="../../ref/request-response.html#django.http.StreamingHttpResponse" title="django.http.StreamingHttpResponse"><tt class="xref py py-class docutils literal"><span class="pre">StreamingHttpResponse</span></tt></a>, reading
the contents of the response will often execute code to generate the
content. Since the view has already returned, such code runs outside of
the transaction.</p>
<p class="last">Generally speaking, it isn&#8217;t advisable to write to the database while
generating a streaming response, since there&#8217;s no sensible way to handle
errors after starting to send the response.</p>
</div>
<p>In practice, this feature simply wraps every view function in the <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a>
decorator described below.</p>
<p>Note that only the execution of your view is enclosed in the transactions.
Middleware runs outside of the transaction, and so does the rendering of
template responses.</p>
<p>When <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASE-ATOMIC_REQUESTS"><tt class="xref std std-setting docutils literal"><span class="pre">ATOMIC_REQUESTS</span></tt></a> is enabled, it&#8217;s
still possible to prevent views from running in a transaction.</p>
<dl class="function">
<dt id="django.db.transaction.non_atomic_requests">
<tt class="descname">non_atomic_requests</tt>(<em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#non_atomic_requests"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.non_atomic_requests" title="Permalink to this definition">¶</a></dt>
<dd><p>This decorator will negate the effect of <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASE-ATOMIC_REQUESTS"><tt class="xref std std-setting docutils literal"><span class="pre">ATOMIC_REQUESTS</span></tt></a> for a given view:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">transaction</span>

<span class="nd">@transaction.non_atomic_requests</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="n">do_stuff</span><span class="p">()</span>

<span class="nd">@transaction.non_atomic_requests</span><span class="p">(</span><span class="n">using</span><span class="o">=</span><span class="s">&#39;other&#39;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_other_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="n">do_stuff_on_the_other_database</span><span class="p">()</span>
</pre></div>
</div>
<p>It only works if it&#8217;s applied to the view itself.</p>
</dd></dl>

<div class="versionchanged">
<span class="title">Changed in Django 1.6:</span> <p>Django used to provide this feature via <tt class="docutils literal"><span class="pre">TransactionMiddleware</span></tt>, which is
now deprecated.</p>
</div>
</div>
<div class="section" id="s-controlling-transactions-explicitly">
<span id="controlling-transactions-explicitly"></span><h3>Controlling transactions explicitly<a class="headerlink" href="#controlling-transactions-explicitly" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<span class="title">New in Django 1.6.</span> </div>
<p>Django provides a single API to control database transactions.</p>
<dl class="function">
<dt id="django.db.transaction.atomic">
<tt class="descname">atomic</tt>(<em>using=None</em>, <em>savepoint=True</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#atomic"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.atomic" title="Permalink to this definition">¶</a></dt>
<dd><p>Atomicity is the defining property of database transactions. <tt class="docutils literal"><span class="pre">atomic</span></tt>
allows us to create a block of code within which the atomicity on the
database is guaranteed. If the block of code is successfully completed, the
changes are committed to the database. If there is an exception, the
changes are rolled back.</p>
<p><tt class="docutils literal"><span class="pre">atomic</span></tt> blocks can be nested. In this case, when an inner block
completes successfully, its effects can still be rolled back if an
exception is raised in the outer block at a later point.</p>
<p><tt class="docutils literal"><span class="pre">atomic</span></tt> is usable both as a <a class="reference external" href="http://docs.python.org/glossary.html#term-decorator">decorator</a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">transaction</span>

<span class="nd">@transaction.atomic</span>
<span class="k">def</span> <span class="nf">viewfunc</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="c"># This code executes inside a transaction.</span>
    <span class="n">do_stuff</span><span class="p">()</span>
</pre></div>
</div>
<p>and as a <a class="reference external" href="http://docs.python.org/glossary.html#term-context-manager">context manager</a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">transaction</span>

<span class="k">def</span> <span class="nf">viewfunc</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="c"># This code executes in autocommit mode (Django&#39;s default).</span>
    <span class="n">do_stuff</span><span class="p">()</span>

    <span class="k">with</span> <span class="n">transaction</span><span class="o">.</span><span class="n">atomic</span><span class="p">():</span>
        <span class="c"># This code executes inside a transaction.</span>
        <span class="n">do_more_stuff</span><span class="p">()</span>
</pre></div>
</div>
<p>Wrapping <tt class="docutils literal"><span class="pre">atomic</span></tt> in a try/except block allows for natural handling of
integrity errors:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">IntegrityError</span><span class="p">,</span> <span class="n">transaction</span>

<span class="nd">@transaction.atomic</span>
<span class="k">def</span> <span class="nf">viewfunc</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="n">create_parent</span><span class="p">()</span>

    <span class="k">try</span><span class="p">:</span>
        <span class="k">with</span> <span class="n">transaction</span><span class="o">.</span><span class="n">atomic</span><span class="p">():</span>
            <span class="n">generate_relationships</span><span class="p">()</span>
    <span class="k">except</span> <span class="n">IntegrityError</span><span class="p">:</span>
        <span class="n">handle_exception</span><span class="p">()</span>

    <span class="n">add_children</span><span class="p">()</span>
</pre></div>
</div>
<p>In this example, even if <tt class="docutils literal"><span class="pre">generate_relationships()</span></tt> causes a database
error by breaking an integrity constraint, you can execute queries in
<tt class="docutils literal"><span class="pre">add_children()</span></tt>, and the changes from <tt class="docutils literal"><span class="pre">create_parent()</span></tt> are still
there. Note that any operations attempted in <tt class="docutils literal"><span class="pre">generate_relationships()</span></tt>
will already have been rolled back safely when <tt class="docutils literal"><span class="pre">handle_exception()</span></tt> is
called, so the exception handler can also operate on the database if
necessary.</p>
<div class="admonition-avoid-catching-exceptions-inside-atomic admonition">
<p class="first admonition-title">Avoid catching exceptions inside <tt class="docutils literal"><span class="pre">atomic</span></tt>!</p>
<p>When exiting an <tt class="docutils literal"><span class="pre">atomic</span></tt> block, Django looks at whether it&#8217;s exited
normally or with an exception to determine whether to commit or roll
back. If you catch and handle exceptions inside an <tt class="docutils literal"><span class="pre">atomic</span></tt> block,
you may hide from Django the fact that a problem has happened. This
can result in unexpected behavior.</p>
<p>This is mostly a concern for <a class="reference internal" href="../../ref/exceptions.html#django.db.DatabaseError" title="django.db.DatabaseError"><tt class="xref py py-exc docutils literal"><span class="pre">DatabaseError</span></tt></a> and its
subclasses such as <a class="reference internal" href="../../ref/exceptions.html#django.db.IntegrityError" title="django.db.IntegrityError"><tt class="xref py py-exc docutils literal"><span class="pre">IntegrityError</span></tt></a>. After such an
error, the transaction is broken and Django will perform a rollback at
the end of the <tt class="docutils literal"><span class="pre">atomic</span></tt> block. If you attempt to run database
queries before the rollback happens, Django will raise a
<a class="reference internal" href="../../ref/exceptions.html#django.db.transaction.TransactionManagementError" title="django.db.transaction.TransactionManagementError"><tt class="xref py py-class docutils literal"><span class="pre">TransactionManagementError</span></tt></a>. You may
also encounter this behavior when an ORM-related signal handler raises
an exception.</p>
<p>The correct way to catch database errors is around an <tt class="docutils literal"><span class="pre">atomic</span></tt> block
as shown above. If necessary, add an extra <tt class="docutils literal"><span class="pre">atomic</span></tt> block for this
purpose. This pattern has another advantage: it delimits explicitly
which operations will be rolled back if an exception occurs.</p>
<p class="last">If you catch exceptions raised by raw SQL queries, Django&#8217;s behavior
is unspecified and database-dependent.</p>
</div>
<p>In order to guarantee atomicity, <tt class="docutils literal"><span class="pre">atomic</span></tt> disables some APIs. Attempting
to commit, roll back, or change the autocommit state of the database
connection within an <tt class="docutils literal"><span class="pre">atomic</span></tt> block will raise an exception.</p>
<p><tt class="docutils literal"><span class="pre">atomic</span></tt> takes a <tt class="docutils literal"><span class="pre">using</span></tt> argument which should be the name of a
database. If this argument isn&#8217;t provided, Django uses the <tt class="docutils literal"><span class="pre">&quot;default&quot;</span></tt>
database.</p>
<p>Under the hood, Django&#8217;s transaction management code:</p>
<ul class="simple">
<li>opens a transaction when entering the outermost <tt class="docutils literal"><span class="pre">atomic</span></tt> block;</li>
<li>creates a savepoint when entering an inner <tt class="docutils literal"><span class="pre">atomic</span></tt> block;</li>
<li>releases or rolls back to the savepoint when exiting an inner block;</li>
<li>commits or rolls back the transaction when exiting the outermost block.</li>
</ul>
<p>You can disable the creation of savepoints for inner blocks by setting the
<tt class="docutils literal"><span class="pre">savepoint</span></tt> argument to <tt class="docutils literal"><span class="pre">False</span></tt>. If an exception occurs, Django will
perform the rollback when exiting the first parent block with a savepoint
if there is one, and the outermost block otherwise. Atomicity is still
guaranteed by the outer transaction. This option should only be used if
the overhead of savepoints is noticeable. It has the drawback of breaking
the error handling described above.</p>
<p>You may use <tt class="docutils literal"><span class="pre">atomic</span></tt> when autocommit is turned off. It will only use
savepoints, even for the outermost block, and it will raise an exception
if the outermost block is declared with <tt class="docutils literal"><span class="pre">savepoint=False</span></tt>.</p>
</dd></dl>

<div class="admonition-performance-considerations admonition">
<p class="first admonition-title">Performance considerations</p>
<p class="last">Open transactions have a performance cost for your database server. To
minimize this overhead, keep your transactions as short as possible. This
is especially important if you&#8217;re using <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a> in long-running
processes, outside of Django&#8217;s request / response cycle.</p>
</div>
</div>
</div>
<div class="section" id="s-autocommit">
<span id="autocommit"></span><h2>Autocommit<a class="headerlink" href="#autocommit" title="Permalink to this headline">¶</a></h2>
<div class="section" id="s-why-django-uses-autocommit">
<span id="s-autocommit-details"></span><span id="why-django-uses-autocommit"></span><span id="autocommit-details"></span><h3>Why Django uses autocommit<a class="headerlink" href="#why-django-uses-autocommit" title="Permalink to this headline">¶</a></h3>
<p>In the SQL standards, each SQL query starts a transaction, unless one is
already active. Such transactions must then be explicitly committed or rolled
back.</p>
<p>This isn&#8217;t always convenient for application developers. To alleviate this
problem, most databases provide an autocommit mode. When autocommit is turned
on and no transaction is active, each SQL query gets wrapped in its own
transaction. In other words, not only does each such query start a
transaction, but the transaction also gets automatically committed or rolled
back, depending on whether the query succeeded.</p>
<p><span class="target" id="index-0"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0249"><strong>PEP 249</strong></a>, the Python Database API Specification v2.0, requires autocommit to
be initially turned off. Django overrides this default and turns autocommit
on.</p>
<p>To avoid this, you can <a class="reference internal" href="#deactivate-transaction-management"><em>deactivate the transaction management</em></a>, but it isn&#8217;t recommended.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.6:</span> <p>Before Django 1.6, autocommit was turned off, and it was emulated by
forcing a commit after write operations in the ORM.</p>
</div>
</div>
<div class="section" id="s-deactivating-transaction-management">
<span id="s-deactivate-transaction-management"></span><span id="deactivating-transaction-management"></span><span id="deactivate-transaction-management"></span><h3>Deactivating transaction management<a class="headerlink" href="#deactivating-transaction-management" title="Permalink to this headline">¶</a></h3>
<p>You can totally disable Django&#8217;s transaction management for a given database
by setting <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASE-AUTOCOMMIT"><tt class="xref std std-setting docutils literal"><span class="pre">AUTOCOMMIT</span></tt></a> to <tt class="docutils literal"><span class="pre">False</span></tt> in its
configuration. If you do this, Django won&#8217;t enable autocommit, and won&#8217;t
perform any commits. You&#8217;ll get the regular behavior of the underlying
database library.</p>
<p>This requires you to commit explicitly every transaction, even those started
by Django or by third-party libraries. Thus, this is best used in situations
where you want to run your own transaction-controlling middleware or do
something really strange.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.6:</span> <p>This used to be controlled by the <tt class="docutils literal"><span class="pre">TRANSACTIONS_MANAGED</span></tt> setting.</p>
</div>
</div>
</div>
<div class="section" id="s-low-level-apis">
<span id="low-level-apis"></span><h2>Low-level APIs<a class="headerlink" href="#low-level-apis" title="Permalink to this headline">¶</a></h2>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p>Always prefer <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a> if possible at all. It accounts for the
idiosyncrasies of each database and prevents invalid operations.</p>
<p class="last">The low level APIs are only useful if you&#8217;re implementing your own
transaction management.</p>
</div>
<div class="section" id="s-managing-autocommit">
<span id="s-id2"></span><span id="managing-autocommit"></span><span id="id2"></span><h3>Autocommit<a class="headerlink" href="#managing-autocommit" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<span class="title">New in Django 1.6.</span> </div>
<p>Django provides a straightforward API in the <a class="reference internal" href="#module-django.db.transaction" title="django.db.transaction"><tt class="xref py py-mod docutils literal"><span class="pre">django.db.transaction</span></tt></a>
module to manage the autocommit state of each database connection.</p>
<dl class="function">
<dt id="django.db.transaction.get_autocommit">
<tt class="descname">get_autocommit</tt>(<em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#get_autocommit"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.get_autocommit" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="function">
<dt id="django.db.transaction.set_autocommit">
<tt class="descname">set_autocommit</tt>(<em>autocommit</em>, <em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#set_autocommit"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.set_autocommit" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>These functions take a <tt class="docutils literal"><span class="pre">using</span></tt> argument which should be the name of a
database. If it isn&#8217;t provided, Django uses the <tt class="docutils literal"><span class="pre">&quot;default&quot;</span></tt> database.</p>
<p>Autocommit is initially turned on. If you turn it off, it&#8217;s your
responsibility to restore it.</p>
<p>Once you turn autocommit off, you get the default behavior of your database
adapter, and Django won&#8217;t help you. Although that behavior is specified in
<span class="target" id="index-1"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0249"><strong>PEP 249</strong></a>, implementations of adapters aren&#8217;t always consistent with one
another. Review the documentation of the adapter you&#8217;re using carefully.</p>
<p>You must ensure that no transaction is active, usually by issuing a
<a class="reference internal" href="#django.db.transaction.commit" title="django.db.transaction.commit"><tt class="xref py py-func docutils literal"><span class="pre">commit()</span></tt></a> or a <a class="reference internal" href="#django.db.transaction.rollback" title="django.db.transaction.rollback"><tt class="xref py py-func docutils literal"><span class="pre">rollback()</span></tt></a>, before turning autocommit back on.</p>
<p>Django will refuse to turn autocommit off when an <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a> block is
active, because that would break atomicity.</p>
</div>
<div class="section" id="s-transactions">
<span id="transactions"></span><h3>Transactions<a class="headerlink" href="#transactions" title="Permalink to this headline">¶</a></h3>
<p>A transaction is an atomic set of database queries. Even if your program
crashes, the database guarantees that either all the changes will be applied,
or none of them.</p>
<p>Django doesn&#8217;t provide an API to start a transaction. The expected way to
start a transaction is to disable autocommit with <a class="reference internal" href="#django.db.transaction.set_autocommit" title="django.db.transaction.set_autocommit"><tt class="xref py py-func docutils literal"><span class="pre">set_autocommit()</span></tt></a>.</p>
<p>Once you&#8217;re in a transaction, you can choose either to apply the changes
you&#8217;ve performed until this point with <a class="reference internal" href="#django.db.transaction.commit" title="django.db.transaction.commit"><tt class="xref py py-func docutils literal"><span class="pre">commit()</span></tt></a>, or to cancel them with
<a class="reference internal" href="#django.db.transaction.rollback" title="django.db.transaction.rollback"><tt class="xref py py-func docutils literal"><span class="pre">rollback()</span></tt></a>. These functions are defined in <a class="reference internal" href="#module-django.db.transaction" title="django.db.transaction"><tt class="xref py py-mod docutils literal"><span class="pre">django.db.transaction</span></tt></a>.</p>
<dl class="function">
<dt id="django.db.transaction.commit">
<tt class="descname">commit</tt>(<em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#commit"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.commit" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="function">
<dt id="django.db.transaction.rollback">
<tt class="descname">rollback</tt>(<em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#rollback"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.rollback" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>These functions take a <tt class="docutils literal"><span class="pre">using</span></tt> argument which should be the name of a
database. If it isn&#8217;t provided, Django uses the <tt class="docutils literal"><span class="pre">&quot;default&quot;</span></tt> database.</p>
<p>Django will refuse to commit or to rollback when an <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a> block is
active, because that would break atomicity.</p>
</div>
<div class="section" id="s-savepoints">
<span id="s-topics-db-transactions-savepoints"></span><span id="savepoints"></span><span id="topics-db-transactions-savepoints"></span><h3>Savepoints<a class="headerlink" href="#savepoints" title="Permalink to this headline">¶</a></h3>
<p>A savepoint is a marker within a transaction that enables you to roll back
part of a transaction, rather than the full transaction. Savepoints are
available with the SQLite (≥ 3.6.8), PostgreSQL, Oracle and MySQL (when using
the InnoDB storage engine) backends. Other backends provide the savepoint
functions, but they&#8217;re empty operations &#8211; they don&#8217;t actually do anything.</p>
<p>Savepoints aren&#8217;t especially useful if you are using autocommit, the default
behavior of Django. However, once you open a transaction with <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a>,
you build up a series of database operations awaiting a commit or rollback. If
you issue a rollback, the entire transaction is rolled back. Savepoints
provide the ability to perform a fine-grained rollback, rather than the full
rollback that would be performed by <tt class="docutils literal"><span class="pre">transaction.rollback()</span></tt>.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.6:</span> <p>When the <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a> decorator is nested, it creates a savepoint to allow
partial commit or rollback. You&#8217;re strongly encouraged to use <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a>
rather than the functions described below, but they&#8217;re still part of the
public API, and there&#8217;s no plan to deprecate them.</p>
</div>
<p>Each of these functions takes a <tt class="docutils literal"><span class="pre">using</span></tt> argument which should be the name of
a database for which the behavior applies.  If no <tt class="docutils literal"><span class="pre">using</span></tt> argument is
provided then the <tt class="docutils literal"><span class="pre">&quot;default&quot;</span></tt> database is used.</p>
<p>Savepoints are controlled by three functions in <a class="reference internal" href="#module-django.db.transaction" title="django.db.transaction"><tt class="xref py py-mod docutils literal"><span class="pre">django.db.transaction</span></tt></a>:</p>
<dl class="function">
<dt id="django.db.transaction.savepoint">
<tt class="descname">savepoint</tt>(<em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#savepoint"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.savepoint" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a new savepoint. This marks a point in the transaction that is
known to be in a &#8220;good&#8221; state. Returns the savepoint ID (<tt class="docutils literal"><span class="pre">sid</span></tt>).</p>
</dd></dl>

<dl class="function">
<dt id="django.db.transaction.savepoint_commit">
<tt class="descname">savepoint_commit</tt>(<em>sid</em>, <em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#savepoint_commit"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.savepoint_commit" title="Permalink to this definition">¶</a></dt>
<dd><p>Releases savepoint <tt class="docutils literal"><span class="pre">sid</span></tt>. The changes performed since the savepoint was
created become part of the transaction.</p>
</dd></dl>

<dl class="function">
<dt id="django.db.transaction.savepoint_rollback">
<tt class="descname">savepoint_rollback</tt>(<em>sid</em>, <em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#savepoint_rollback"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.savepoint_rollback" title="Permalink to this definition">¶</a></dt>
<dd><p>Rolls back the transaction to savepoint <tt class="docutils literal"><span class="pre">sid</span></tt>.</p>
</dd></dl>

<p>These functions do nothing if savepoints aren&#8217;t supported or if the database
is in autocommit mode.</p>
<p>In addition, there&#8217;s a utility function:</p>
<dl class="function">
<dt id="django.db.transaction.clean_savepoints">
<tt class="descname">clean_savepoints</tt>(<em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#clean_savepoints"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.clean_savepoints" title="Permalink to this definition">¶</a></dt>
<dd><p>Resets the counter used to generate unique savepoint IDs.</p>
</dd></dl>

<p>The following example demonstrates the use of savepoints:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">transaction</span>

<span class="c"># open a transaction</span>
<span class="nd">@transaction.atomic</span>
<span class="k">def</span> <span class="nf">viewfunc</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>

    <span class="n">a</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
    <span class="c"># transaction now contains a.save()</span>

    <span class="n">sid</span> <span class="o">=</span> <span class="n">transaction</span><span class="o">.</span><span class="n">savepoint</span><span class="p">()</span>

    <span class="n">b</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
    <span class="c"># transaction now contains a.save() and b.save()</span>

    <span class="k">if</span> <span class="n">want_to_keep_b</span><span class="p">:</span>
        <span class="n">transaction</span><span class="o">.</span><span class="n">savepoint_commit</span><span class="p">(</span><span class="n">sid</span><span class="p">)</span>
        <span class="c"># open transaction still contains a.save() and b.save()</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">transaction</span><span class="o">.</span><span class="n">savepoint_rollback</span><span class="p">(</span><span class="n">sid</span><span class="p">)</span>
        <span class="c"># open transaction now contains only a.save()</span>
</pre></div>
</div>
<div class="versionadded">
<span class="title">New in Django 1.6.</span> </div>
<p>Savepoints may be used to recover from a database error by performing a partial
rollback. If you&#8217;re doing this inside an <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a> block, the entire block
will still be rolled back, because it doesn&#8217;t know you&#8217;ve handled the situation
at a lower level! To prevent this, you can control the rollback behavior with
the following functions.</p>
<dl class="function">
<dt id="django.db.transaction.get_rollback">
<tt class="descname">get_rollback</tt>(<em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#get_rollback"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.get_rollback" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="function">
<dt id="django.db.transaction.set_rollback">
<tt class="descname">set_rollback</tt>(<em>rollback</em>, <em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/transaction.html#set_rollback"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.set_rollback" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Setting the rollback flag to <tt class="docutils literal"><span class="pre">True</span></tt> forces a rollback when exiting the
innermost atomic block. This may be useful to trigger a rollback without
raising an exception.</p>
<p>Setting it to <tt class="docutils literal"><span class="pre">False</span></tt> prevents such a rollback. Before doing that, make sure
you&#8217;ve rolled back the transaction to a known-good savepoint within the current
atomic block! Otherwise you&#8217;re breaking atomicity and data corruption may
occur.</p>
</div>
</div>
<div class="section" id="s-database-specific-notes">
<span id="database-specific-notes"></span><h2>Database-specific notes<a class="headerlink" href="#database-specific-notes" title="Permalink to this headline">¶</a></h2>
<div class="section" id="s-savepoints-in-sqlite">
<span id="s-id3"></span><span id="savepoints-in-sqlite"></span><span id="id3"></span><h3>Savepoints in SQLite<a class="headerlink" href="#savepoints-in-sqlite" title="Permalink to this headline">¶</a></h3>
<p>While SQLite ≥ 3.6.8 supports savepoints, a flaw in the design of the
<a class="reference external" href="http://docs.python.org/3/library/sqlite3.html#module-sqlite3" title="(in Python v3.4)"><tt class="xref py py-mod docutils literal"><span class="pre">sqlite3</span></tt></a> module makes them hardly usable.</p>
<p>When autocommit is enabled, savepoints don&#8217;t make sense. When it&#8217;s disabled,
<a class="reference external" href="http://docs.python.org/3/library/sqlite3.html#module-sqlite3" title="(in Python v3.4)"><tt class="xref py py-mod docutils literal"><span class="pre">sqlite3</span></tt></a> commits implicitly before savepoint statements. (In fact, it
commits before any statement other than <tt class="docutils literal"><span class="pre">SELECT</span></tt>, <tt class="docutils literal"><span class="pre">INSERT</span></tt>, <tt class="docutils literal"><span class="pre">UPDATE</span></tt>,
<tt class="docutils literal"><span class="pre">DELETE</span></tt> and <tt class="docutils literal"><span class="pre">REPLACE</span></tt>.) This bug has two consequences:</p>
<ul class="simple">
<li>The low level APIs for savepoints are only usable inside a transaction ie.
inside an <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a> block.</li>
<li>It&#8217;s impossible to use <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a> when autocommit is turned off.</li>
</ul>
</div>
<div class="section" id="s-transactions-in-mysql">
<span id="transactions-in-mysql"></span><h3>Transactions in MySQL<a class="headerlink" href="#transactions-in-mysql" title="Permalink to this headline">¶</a></h3>
<p>If you&#8217;re using MySQL, your tables may or may not support transactions; it
depends on your MySQL version and the table types you&#8217;re using. (By
&#8220;table types,&#8221; we mean something like &#8220;InnoDB&#8221; or &#8220;MyISAM&#8221;.) MySQL transaction
peculiarities are outside the scope of this article, but the MySQL site has
<a class="reference external" href="http://dev.mysql.com/doc/refman/5.6/en/sql-syntax-transactions.html">information on MySQL transactions</a>.</p>
<p>If your MySQL setup does <em>not</em> support transactions, then Django will always
function in autocommit mode: statements will be executed and committed as soon
as they&#8217;re called. If your MySQL setup <em>does</em> support transactions, Django
will handle transactions as explained in this document.</p>
</div>
<div class="section" id="s-handling-exceptions-within-postgresql-transactions">
<span id="handling-exceptions-within-postgresql-transactions"></span><h3>Handling exceptions within PostgreSQL transactions<a class="headerlink" href="#handling-exceptions-within-postgresql-transactions" title="Permalink to this headline">¶</a></h3>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This section is relevant only if you&#8217;re implementing your own transaction
management. This problem cannot occur in Django&#8217;s default mode and
<a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a> handles it automatically.</p>
</div>
<p>Inside a transaction, when a call to a PostgreSQL cursor raises an exception
(typically <tt class="docutils literal"><span class="pre">IntegrityError</span></tt>), all subsequent SQL in the same transaction
will fail with the error &#8220;current transaction is aborted, queries ignored
until end of transaction block&#8221;. Whilst simple use of <tt class="docutils literal"><span class="pre">save()</span></tt> is unlikely
to raise an exception in PostgreSQL, there are more advanced usage patterns
which might, such as saving objects with unique fields, saving using the
force_insert/force_update flag, or invoking custom SQL.</p>
<p>There are several ways to recover from this sort of error.</p>
<div class="section" id="s-transaction-rollback">
<span id="transaction-rollback"></span><h4>Transaction rollback<a class="headerlink" href="#transaction-rollback" title="Permalink to this headline">¶</a></h4>
<p>The first option is to roll back the entire transaction. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">a</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c"># Succeeds, but may be undone by transaction rollback</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">b</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c"># Could throw exception</span>
<span class="k">except</span> <span class="n">IntegrityError</span><span class="p">:</span>
    <span class="n">transaction</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
<span class="n">c</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c"># Succeeds, but a.save() may have been undone</span>
</pre></div>
</div>
<p>Calling <tt class="docutils literal"><span class="pre">transaction.rollback()</span></tt> rolls back the entire transaction. Any
uncommitted database operations will be lost. In this example, the changes
made by <tt class="docutils literal"><span class="pre">a.save()</span></tt> would be lost, even though that operation raised no error
itself.</p>
</div>
<div class="section" id="s-savepoint-rollback">
<span id="savepoint-rollback"></span><h4>Savepoint rollback<a class="headerlink" href="#savepoint-rollback" title="Permalink to this headline">¶</a></h4>
<p>You can use <a class="reference internal" href="#topics-db-transactions-savepoints"><em>savepoints</em></a> to control
the extent of a rollback. Before performing a database operation that could
fail, you can set or update the savepoint; that way, if the operation fails,
you can roll back the single offending operation, rather than the entire
transaction. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">a</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c"># Succeeds, and never undone by savepoint rollback</span>
<span class="n">sid</span> <span class="o">=</span> <span class="n">transaction</span><span class="o">.</span><span class="n">savepoint</span><span class="p">()</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">b</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c"># Could throw exception</span>
    <span class="n">transaction</span><span class="o">.</span><span class="n">savepoint_commit</span><span class="p">(</span><span class="n">sid</span><span class="p">)</span>
<span class="k">except</span> <span class="n">IntegrityError</span><span class="p">:</span>
    <span class="n">transaction</span><span class="o">.</span><span class="n">savepoint_rollback</span><span class="p">(</span><span class="n">sid</span><span class="p">)</span>
<span class="n">c</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c"># Succeeds, and a.save() is never undone</span>
</pre></div>
</div>
<p>In this example, <tt class="docutils literal"><span class="pre">a.save()</span></tt> will not be undone in the case where
<tt class="docutils literal"><span class="pre">b.save()</span></tt> raises an exception.</p>
</div>
</div>
</div>
<div class="section" id="s-changes-from-django-1-5-and-earlier">
<span id="s-transactions-upgrading-from-1-5"></span><span id="changes-from-django-1-5-and-earlier"></span><span id="transactions-upgrading-from-1-5"></span><h2>Changes from Django 1.5 and earlier<a class="headerlink" href="#changes-from-django-1-5-and-earlier" title="Permalink to this headline">¶</a></h2>
<p>The features described below were deprecated in Django 1.6 and will be removed
in Django 1.8. They&#8217;re documented in order to ease the migration to the new
transaction management APIs.</p>
<div class="section" id="s-legacy-apis">
<span id="legacy-apis"></span><h3>Legacy APIs<a class="headerlink" href="#legacy-apis" title="Permalink to this headline">¶</a></h3>
<p>The following functions, defined in <tt class="docutils literal"><span class="pre">django.db.transaction</span></tt>, provided a way
to control transactions on a per-function or per-code-block basis. They could
be used as decorators or as context managers, and they accepted a <tt class="docutils literal"><span class="pre">using</span></tt>
argument, exactly like <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a>.</p>
<dl class="function">
<dt id="django.db.transaction.autocommit">
<tt class="descname">autocommit</tt>()<a class="reference internal" href="../../_modules/django/db/transaction.html#autocommit"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.autocommit" title="Permalink to this definition">¶</a></dt>
<dd><p>Enable Django&#8217;s default autocommit behavior.</p>
<p>Transactions will be committed as soon as you call <tt class="docutils literal"><span class="pre">model.save()</span></tt>,
<tt class="docutils literal"><span class="pre">model.delete()</span></tt>, or any other function that writes to the database.</p>
</dd></dl>

<dl class="function">
<dt id="django.db.transaction.commit_on_success">
<tt class="descname">commit_on_success</tt>()<a class="reference internal" href="../../_modules/django/db/transaction.html#commit_on_success"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.commit_on_success" title="Permalink to this definition">¶</a></dt>
<dd><p>Use a single transaction for all the work done in a function.</p>
<p>If the function returns successfully, then Django will commit all work done
within the function at that point. If the function raises an exception,
though, Django will roll back the transaction.</p>
</dd></dl>

<dl class="function">
<dt id="django.db.transaction.commit_manually">
<tt class="descname">commit_manually</tt>()<a class="reference internal" href="../../_modules/django/db/transaction.html#commit_manually"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.transaction.commit_manually" title="Permalink to this definition">¶</a></dt>
<dd><p>Tells Django you&#8217;ll be managing the transaction on your own.</p>
<p>Whether you are writing or simply reading from the database, you must
<tt class="docutils literal"><span class="pre">commit()</span></tt> or <tt class="docutils literal"><span class="pre">rollback()</span></tt> explicitly or Django will raise a
<a class="reference internal" href="../../ref/exceptions.html#django.db.transaction.TransactionManagementError" title="django.db.transaction.TransactionManagementError"><tt class="xref py py-exc docutils literal"><span class="pre">TransactionManagementError</span></tt></a> exception. This is required when reading
from the database because <tt class="docutils literal"><span class="pre">SELECT</span></tt> statements may call functions which
modify tables, and thus it is impossible to know if any data has been
modified.</p>
</dd></dl>

</div>
<div class="section" id="s-transaction-states">
<span id="s-id4"></span><span id="transaction-states"></span><span id="id4"></span><h3>Transaction states<a class="headerlink" href="#transaction-states" title="Permalink to this headline">¶</a></h3>
<p>The three functions described above relied on a concept called &#8220;transaction
states&#8221;. This mechanism was deprecated in Django 1.6, but it&#8217;s still available
until Django 1.8.</p>
<p>At any time, each database connection is in one of these two states:</p>
<ul class="simple">
<li><strong>auto mode</strong>: autocommit is enabled;</li>
<li><strong>managed mode</strong>: autocommit is disabled.</li>
</ul>
<p>Django starts in auto mode. <tt class="docutils literal"><span class="pre">TransactionMiddleware</span></tt>,
<a class="reference internal" href="#django.db.transaction.commit_on_success" title="django.db.transaction.commit_on_success"><tt class="xref py py-func docutils literal"><span class="pre">commit_on_success()</span></tt></a> and <a class="reference internal" href="#django.db.transaction.commit_manually" title="django.db.transaction.commit_manually"><tt class="xref py py-func docutils literal"><span class="pre">commit_manually()</span></tt></a> activate managed mode;
<a class="reference internal" href="#django.db.transaction.autocommit" title="django.db.transaction.autocommit"><tt class="xref py py-func docutils literal"><span class="pre">autocommit()</span></tt></a> activates auto mode.</p>
<p>Internally, Django keeps a stack of states. Activations and deactivations must
be balanced.</p>
<p>For example, <a class="reference internal" href="#django.db.transaction.commit_on_success" title="django.db.transaction.commit_on_success"><tt class="xref py py-func docutils literal"><span class="pre">commit_on_success()</span></tt></a> switches to managed mode when entering
the block of code it controls; when exiting the block, it commits or
rollbacks, and switches back to auto mode.</p>
<p>So <a class="reference internal" href="#django.db.transaction.commit_on_success" title="django.db.transaction.commit_on_success"><tt class="xref py py-func docutils literal"><span class="pre">commit_on_success()</span></tt></a> really has two effects: it changes the
transaction state and it defines a transaction block. Nesting will give the
expected results in terms of transaction state, but not in terms of
transaction semantics. Most often, the inner block will commit, breaking the
atomicity of the outer block.</p>
<p><a class="reference internal" href="#django.db.transaction.autocommit" title="django.db.transaction.autocommit"><tt class="xref py py-func docutils literal"><span class="pre">autocommit()</span></tt></a> and <a class="reference internal" href="#django.db.transaction.commit_manually" title="django.db.transaction.commit_manually"><tt class="xref py py-func docutils literal"><span class="pre">commit_manually()</span></tt></a> have similar limitations.</p>
</div>
<div class="section" id="s-api-changes">
<span id="api-changes"></span><h3>API changes<a class="headerlink" href="#api-changes" title="Permalink to this headline">¶</a></h3>
<div class="section" id="s-transaction-middleware">
<span id="transaction-middleware"></span><h4>Transaction middleware<a class="headerlink" href="#transaction-middleware" title="Permalink to this headline">¶</a></h4>
<p>In Django 1.6, <tt class="docutils literal"><span class="pre">TransactionMiddleware</span></tt> is deprecated and replaced by
<a class="reference internal" href="../../ref/settings.html#std:setting-DATABASE-ATOMIC_REQUESTS"><tt class="xref std std-setting docutils literal"><span class="pre">ATOMIC_REQUESTS</span></tt></a>. While the general
behavior is the same, there are two differences.</p>
<p>With the previous API, it was possible to switch to autocommit or to commit
explicitly anywhere inside a view. Since <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASE-ATOMIC_REQUESTS"><tt class="xref std std-setting docutils literal"><span class="pre">ATOMIC_REQUESTS</span></tt></a> relies on <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a> which enforces atomicity,
this isn&#8217;t allowed any longer. However, at the top level, it&#8217;s still possible
to avoid wrapping an entire view in a transaction. To achieve this, decorate
the view with <a class="reference internal" href="#django.db.transaction.non_atomic_requests" title="django.db.transaction.non_atomic_requests"><tt class="xref py py-func docutils literal"><span class="pre">non_atomic_requests()</span></tt></a> instead of <a class="reference internal" href="#django.db.transaction.autocommit" title="django.db.transaction.autocommit"><tt class="xref py py-func docutils literal"><span class="pre">autocommit()</span></tt></a>.</p>
<p>The transaction middleware applied not only to view functions, but also to
middleware modules that came after it. For instance, if you used the session
middleware after the transaction middleware, session creation was part of the
transaction. <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASE-ATOMIC_REQUESTS"><tt class="xref std std-setting docutils literal"><span class="pre">ATOMIC_REQUESTS</span></tt></a> only
applies to the view itself.</p>
</div>
<div class="section" id="s-managing-transactions">
<span id="managing-transactions"></span><h4>Managing transactions<a class="headerlink" href="#managing-transactions" title="Permalink to this headline">¶</a></h4>
<p>Starting with Django 1.6, <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a> is the only supported API for
defining a transaction. Unlike the deprecated APIs, it&#8217;s nestable and always
guarantees atomicity.</p>
<p>In most cases, it will be a drop-in replacement for <a class="reference internal" href="#django.db.transaction.commit_on_success" title="django.db.transaction.commit_on_success"><tt class="xref py py-func docutils literal"><span class="pre">commit_on_success()</span></tt></a>.</p>
<p>During the deprecation period, it&#8217;s possible to use <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a> within
<a class="reference internal" href="#django.db.transaction.autocommit" title="django.db.transaction.autocommit"><tt class="xref py py-func docutils literal"><span class="pre">autocommit()</span></tt></a>, <a class="reference internal" href="#django.db.transaction.commit_on_success" title="django.db.transaction.commit_on_success"><tt class="xref py py-func docutils literal"><span class="pre">commit_on_success()</span></tt></a> or <a class="reference internal" href="#django.db.transaction.commit_manually" title="django.db.transaction.commit_manually"><tt class="xref py py-func docutils literal"><span class="pre">commit_manually()</span></tt></a>.
However, the reverse is forbidden, because nesting the old decorators /
context managers breaks atomicity.</p>
</div>
<div class="section" id="s-id5">
<span id="id5"></span><h4>Managing autocommit<a class="headerlink" href="#id5" title="Permalink to this headline">¶</a></h4>
<p>Django 1.6 introduces an explicit <a class="reference internal" href="#managing-autocommit"><em>API for managing autocommit</em></a>.</p>
<p>To disable autocommit temporarily, instead of:</p>
<div class="highlight-python"><div class="highlight"><pre>with transaction.commit_manually():
    # do stuff
</pre></div>
</div>
<p>you should now use:</p>
<div class="highlight-python"><div class="highlight"><pre>transaction.set_autocommit(False)
try:
    # do stuff
finally:
    transaction.set_autocommit(True)
</pre></div>
</div>
<p>To enable autocommit temporarily, instead of:</p>
<div class="highlight-python"><div class="highlight"><pre>with transaction.autocommit():
    # do stuff
</pre></div>
</div>
<p>you should now use:</p>
<div class="highlight-python"><div class="highlight"><pre>transaction.set_autocommit(True)
try:
    # do stuff
finally:
    transaction.set_autocommit(False)
</pre></div>
</div>
<p>Unless you&#8217;re implementing a transaction management framework, you shouldn&#8217;t
ever need to do this.</p>
</div>
<div class="section" id="s-disabling-transaction-management">
<span id="disabling-transaction-management"></span><h4>Disabling transaction management<a class="headerlink" href="#disabling-transaction-management" title="Permalink to this headline">¶</a></h4>
<p>Instead of setting <tt class="docutils literal"><span class="pre">TRANSACTIONS_MANAGED</span> <span class="pre">=</span> <span class="pre">True</span></tt>, set the <tt class="docutils literal"><span class="pre">AUTOCOMMIT</span></tt> key
to <tt class="docutils literal"><span class="pre">False</span></tt> in the configuration of each database, as explained in
<a class="reference internal" href="#deactivate-transaction-management"><em>Deactivating transaction management</em></a>.</p>
</div>
</div>
<div class="section" id="s-backwards-incompatibilities">
<span id="backwards-incompatibilities"></span><h3>Backwards incompatibilities<a class="headerlink" href="#backwards-incompatibilities" title="Permalink to this headline">¶</a></h3>
<p>Since version 1.6, Django uses database-level autocommit in auto mode.
Previously, it implemented application-level autocommit by triggering a commit
after each ORM write.</p>
<p>As a consequence, each database query (for instance, an ORM read) started a
transaction that lasted until the next ORM write. Such &#8220;automatic
transactions&#8221; no longer exist in Django 1.6.</p>
<p>There are four known scenarios where this is backwards-incompatible.</p>
<p>Note that managed mode isn&#8217;t affected at all. This section assumes auto mode.
See the <a class="reference internal" href="#transaction-states"><em>description of modes</em></a> above.</p>
<div class="section" id="s-sequences-of-custom-sql-queries">
<span id="sequences-of-custom-sql-queries"></span><h4>Sequences of custom SQL queries<a class="headerlink" href="#sequences-of-custom-sql-queries" title="Permalink to this headline">¶</a></h4>
<p>If you&#8217;re executing several <a class="reference internal" href="sql.html#executing-custom-sql"><em>custom SQL queries</em></a>
in a row, each one now runs in its own transaction, instead of sharing the
same &#8220;automatic transaction&#8221;. If you need to enforce atomicity, you must wrap
the sequence of queries in <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a>.</p>
<p>To check for this problem, look for calls to <tt class="docutils literal"><span class="pre">cursor.execute()</span></tt>. They&#8217;re
usually followed by a call to <tt class="docutils literal"><span class="pre">transaction.commit_unless_managed()</span></tt>, which
isn&#8217;t useful any more and should be removed.</p>
</div>
<div class="section" id="s-select-for-update">
<span id="select-for-update"></span><h4>Select for update<a class="headerlink" href="#select-for-update" title="Permalink to this headline">¶</a></h4>
<p>If you were relying on &#8220;automatic transactions&#8221; to provide locking between
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.select_for_update" title="django.db.models.query.QuerySet.select_for_update"><tt class="xref py py-meth docutils literal"><span class="pre">select_for_update()</span></tt></a> and a subsequent
write operation — an extremely fragile design, but nonetheless possible — you
must wrap the relevant code in <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a>. Since Django 1.6.3, executing
a query with <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.select_for_update" title="django.db.models.query.QuerySet.select_for_update"><tt class="xref py py-meth docutils literal"><span class="pre">select_for_update()</span></tt></a> in
autocommit mode will raise a
<a class="reference internal" href="../../ref/exceptions.html#django.db.transaction.TransactionManagementError" title="django.db.transaction.TransactionManagementError"><tt class="xref py py-exc docutils literal"><span class="pre">TransactionManagementError</span></tt></a>.</p>
</div>
<div class="section" id="s-using-a-high-isolation-level">
<span id="using-a-high-isolation-level"></span><h4>Using a high isolation level<a class="headerlink" href="#using-a-high-isolation-level" title="Permalink to this headline">¶</a></h4>
<p>If you were using the &#8220;repeatable read&#8221; isolation level or higher, and if you
relied on &#8220;automatic transactions&#8221; to guarantee consistency between successive
reads, the new behavior might be backwards-incompatible. To enforce
consistency, you must wrap such sequences in <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a>.</p>
<p>MySQL defaults to &#8220;repeatable read&#8221; and SQLite to &#8220;serializable&#8221;; they may be
affected by this problem.</p>
<p>At the &#8220;read committed&#8221; isolation level or lower, &#8220;automatic transactions&#8221;
have no effect on the semantics of any sequence of ORM operations.</p>
<p>PostgreSQL and Oracle default to &#8220;read committed&#8221; and aren&#8217;t affected, unless
you changed the isolation level.</p>
</div>
<div class="section" id="s-using-unsupported-database-features">
<span id="using-unsupported-database-features"></span><h4>Using unsupported database features<a class="headerlink" href="#using-unsupported-database-features" title="Permalink to this headline">¶</a></h4>
<p>With triggers, views, or functions, it&#8217;s possible to make ORM reads result in
database modifications. Django 1.5 and earlier doesn&#8217;t deal with this case and
it&#8217;s theoretically possible to observe a different behavior after upgrading to
Django 1.6 or later. In doubt, use <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a> to enforce integrity.</p>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Database transactions</a><ul>
<li><a class="reference internal" href="#managing-database-transactions">Managing database transactions</a><ul>
<li><a class="reference internal" href="#django-s-default-transaction-behavior">Django&#8217;s default transaction behavior</a></li>
<li><a class="reference internal" href="#tying-transactions-to-http-requests">Tying transactions to HTTP requests</a></li>
<li><a class="reference internal" href="#controlling-transactions-explicitly">Controlling transactions explicitly</a></li>
</ul>
</li>
<li><a class="reference internal" href="#autocommit">Autocommit</a><ul>
<li><a class="reference internal" href="#why-django-uses-autocommit">Why Django uses autocommit</a></li>
<li><a class="reference internal" href="#deactivating-transaction-management">Deactivating transaction management</a></li>
</ul>
</li>
<li><a class="reference internal" href="#low-level-apis">Low-level APIs</a><ul>
<li><a class="reference internal" href="#managing-autocommit">Autocommit</a></li>
<li><a class="reference internal" href="#transactions">Transactions</a></li>
<li><a class="reference internal" href="#savepoints">Savepoints</a></li>
</ul>
</li>
<li><a class="reference internal" href="#database-specific-notes">Database-specific notes</a><ul>
<li><a class="reference internal" href="#savepoints-in-sqlite">Savepoints in SQLite</a></li>
<li><a class="reference internal" href="#transactions-in-mysql">Transactions in MySQL</a></li>
<li><a class="reference internal" href="#handling-exceptions-within-postgresql-transactions">Handling exceptions within PostgreSQL transactions</a><ul>
<li><a class="reference internal" href="#transaction-rollback">Transaction rollback</a></li>
<li><a class="reference internal" href="#savepoint-rollback">Savepoint rollback</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#changes-from-django-1-5-and-earlier">Changes from Django 1.5 and earlier</a><ul>
<li><a class="reference internal" href="#legacy-apis">Legacy APIs</a></li>
<li><a class="reference internal" href="#transaction-states">Transaction states</a></li>
<li><a class="reference internal" href="#api-changes">API changes</a><ul>
<li><a class="reference internal" href="#transaction-middleware">Transaction middleware</a></li>
<li><a class="reference internal" href="#managing-transactions">Managing transactions</a></li>
<li><a class="reference internal" href="#id5">Managing autocommit</a></li>
<li><a class="reference internal" href="#disabling-transaction-management">Disabling transaction management</a></li>
</ul>
</li>
<li><a class="reference internal" href="#backwards-incompatibilities">Backwards incompatibilities</a><ul>
<li><a class="reference internal" href="#sequences-of-custom-sql-queries">Sequences of custom SQL queries</a></li>
<li><a class="reference internal" href="#select-for-update">Select for update</a></li>
<li><a class="reference internal" href="#using-a-high-isolation-level">Using a high isolation level</a></li>
<li><a class="reference internal" href="#using-unsupported-database-features">Using unsupported database features</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="sql.html">Performing raw SQL queries</a></li>
    
    
      <li>Next: <a href="multi-db.html">Multiple databases</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../../index.html">Django 1.7.8.dev20150401230226 documentation</a>
        
          <ul><li><a href="../index.html">Using Django</a>
        
          <ul><li><a href="index.html">Models and databases</a>
        
        <ul><li>Database transactions</li></ul>
        </li></ul></li></ul>
      </li>
  </ul>

  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="../../_sources/topics/db/transactions.txt"
           rel="nofollow">Show Source</a></li>
  </ul>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Apr 02, 2015</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="sql.html" title="Performing raw SQL queries">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="multi-db.html" title="Multiple databases">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>